import socket

list_str = '''
test01  188.188.0.114   22
test02  111.111.11.11   13400
test03  192.168.1.102   3306
'''

OK_list = []
Timeout_list = []
DOWN_list = []
ip_list = list(list_str.split())


def IsOpen(hostname, ip, port):
    socket.setdefaulttimeout(2)
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect((ip, port))
        s.shutdown(2)
        OK_list.append([hostname, ip, port])
        return True
    except socket.timeout:
        Timeout_list.append([hostname, ip, port])
        return False
    except Exception:
        DOWN_list.append([hostname, ip, port])
        return False


if __name__ == '__main__':
    for _ in range(0, len(ip_list), 3):
        IsOpen(str(ip_list[_]), str(ip_list[_ + 1]), int(ip_list[_ + 2]))
    lists = {'正常连接': OK_list, '连接超时': Timeout_list, '宕机': DOWN_list}
    for status, _ in lists.items():
        print(status.center(40, '-'))
        if not _:
            print('null')
            continue
        for hostname, ip, port in _:
            # print('hostname: %s ,ip: %s ,port: %d' % (hostname, ip, port))
            # format格式化打印输出结果
            print('hostname: {0},ip: {1},port: {2}'.format(hostname, ip, port))